package com.neu.wangxiaoyang.dao;

import com.neu.commons.Dao.BaseDao;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class GenerateSqlDao extends BaseDao {
    private String tableName;
    private String pkName;
    private String seqName;

    public GenerateSqlDao(String tableName, String pkName, String seqName) {
        this.tableName = tableName;
        this.pkName = pkName;
        this.seqName = seqName;
    }

    public  final int insert(Map<String,String> item){
        int row=0;
        String sql="insert into "+tableName+"("+pkName+",";
        String values=") values("+seqName+".nextval,";

        List list=new ArrayList();//存放每一个?对应的值
        for(Map.Entry<String,String> entry:item.entrySet()){
            String key=entry.getKey();//获取的就是列名
            String value=entry.getValue();
            sql+=key+",";
            values+="?,";
            list.add(value);
        }
        sql=sql.substring(0,sql.length()-1);
        values=values.substring(0,values.length()-1);
        sql+=values+")";
        System.out.println(sql);
        row=super.BaseDaoUpdate(sql,list.toArray());
        return row;
    }
    public final int delete(Map<String,String> item){
        int row=0;
        String sql="delete from "+tableName;
        sql+=" where "+pkName+"=?";
        row=super.BaseDaoUpdate(sql,item.get(pkName));
        return row;
    }
    public final int update(Map<String,String> item){
        int row=0;
        String sql="update "+tableName+" set ";
        String set="";
        List param=new ArrayList();
        for (Map.Entry<String,String> entry:item.entrySet()){
            String columnName=entry.getKey();
            String value=entry.getValue();
            set+=","+columnName+"=?";
            param.add(value);
        }
        sql+=set.substring(1);
        sql+=" where "+pkName+"=?";
        param.add(item.get(pkName));
        row=super.BaseDaoUpdate(sql,param.toArray());
        return row;
    }
    //完成所有等值查询的操作
    //就是我们会上网 使用的高级搜索
    //param.put("u_name","aaa");
    public List<Map<String,Object>> findByEqualsParam(Map<String,String> param){
        List<Map<String,Object>> list=null;
        String sql="select * from "+tableName+" where 1=1 ";
        List params=new ArrayList();
        if(param!=null){
            //动态拼接查询条件
            for(Map.Entry<String,String> entry:param.entrySet()){
                sql+=" and "+entry.getKey()+"=? "; // u_name=?
                params.add(entry.getValue());
            }
        }
        System.out.println(sql);
        list=super.BaseDaoQuery(sql,params.toArray());
        return list;
    }
}
